//
//  HTimeManager.swift
//  Drop
//
//  Created by hushaohua on 2017/11/14.
//  Copyright © 2017年 init. All rights reserved.
//

import UIKit

protocol HTimeObserver {
    func intervalScheduled(_ timestampFromReference:TimeInterval) -> Void;
}

class HTimeManager {
    static let sharedInstance = HTimeManager();
    class func sharedManager() -> HTimeManager {
        return sharedInstance;
    }
    
    lazy var observers:[HTimeObserver] = {
        var array:[HTimeObserver] = [HTimeObserver]();
        return array;
    }();
    
    func isObserver(_ aObserver:HTimeObserver) -> Bool {
        return self.indexOfObserver(aObserver) != nil;
    }
    
    func indexOfObserver(_ aObserver : HTimeObserver) -> Int?{
        let aObject:AnyObject = aObserver as AnyObject;
        var index:Int = 0;
        for observer in self.observers {
            let object:AnyObject = observer as AnyObject;
            if (aObject.isEqual(object)){
                return index;
            }
            index += 1;
        }
        return nil;
    }
    
    func addObserver(_ observer : HTimeObserver) -> Void {
        self.observers.append(observer);
    }
    
    func removeObserver(_ observer : HTimeObserver) -> Void {
        let index:Int? = self.indexOfObserver(observer);
        if (index != nil){
            self.observers.remove(at: index!);
        }
    }
    
    init() {
        self.startTimer();
    }
    
    var timer:Timer?;
    
    func startTimer() -> Void {
        self.stopTimer();
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timeScheduled(_:)), userInfo: nil, repeats: true);
    }
    
    func stopTimer() -> Void{
        if (timer != nil){
            self.timer?.invalidate();
            self.timer = nil;
        }
    }
    
    @objc func timeScheduled(_ timer:Timer) -> Void {
        for observer in self.observers {
            observer.intervalScheduled(Date.timeIntervalSinceReferenceDate);
        }
    }
}
